package com.feihong.yw189.paidan.qiangdanservice;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.text.TextUtils;
import android.util.Log;

import com.feihong.yw189.R;
import com.feihong.yw189.activity.shouye.MainActivity;
import com.feihong.yw189.app.App;
import com.feihong.yw189.bluetooth.utils.util.ToastUtils;
import com.feihong.yw189.listener.http.RequestCallBack;
import com.feihong.yw189.paidan.activity.DispatchActivity;
import com.feihong.yw189.paidan.qiangdanservice.daemonservice.AbsWorkService;
import com.feihong.yw189.paidan.qiangdanservice.notification.BaseBuilder;
import com.feihong.yw189.paidan.qiangdanservice.notification.NotifyUtil;
import com.feihong.yw189.paidan.tools.RefReshToken;

import org.xutils.common.Callback;

import io.reactivex.disposables.Disposable;

/**
 * Created by Sabirjan on 2018/2/3.
 */

public class PaiDanService extends AbsWorkService implements MediaPlayer.OnCompletionListener {

    private final int RES_ID = R.raw.xinxiaoxi;
    private static final int NOT_ID = 20015;
    private static final int NOT_ID2 = 20016;
    private static final String TAG = "派单";
    //是否 任务完成, 不再需要服务运行?
    public static boolean sShouldStopService;
    public static Disposable sDisposable;
    public static LocationTools locationTools;
    private int count = 0;
    public static boolean isRunning = false;
    private MediaPlayer mediaPlayer;
    private boolean isPlayningNewOrder = false;

    public static void stopService() {
        //我们现在不再需要服务运行了, 将标志位置为 true
        Log.i(TAG, "stopService: 服务停止....");
        isRunning = false;
        sShouldStopService = true;
        //取消对任务的订阅
        if (locationTools != null) {
            locationTools.stopLocation();
        }
        //取消 Job / Alarm / Subscription
        cancelJobAlarmSub();
    }

    private void initLocationTools() {
        try {
            if (locationTools != null) {
                locationTools.stopLocation();
                locationTools = null;
            }
            NotifyUtil.init(this);
            NotifyUtil.cancel(NOT_ID);

        } catch (Exception ex) {
        }
        isRunning = false;
        locationTools = new LocationTools(this, mLocationCallBack);

    }

    /**
     * 是否 任务完成, 不再需要服务运行?
     *
     * @return 应当停止服务, true; 应当启动服务, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean shouldStopService(Intent intent, int flags, int startId) {
        Log.i(TAG, "shouldStopService: sShouldStopService=" + sShouldStopService);
        return sShouldStopService;
    }

    private LocationCallBack mLocationCallBack = new LocationCallBack() {

        @Override
        public void successGetLocation(LocationInfo info) {
            if (info != null) {
                String Latitude = info.getLatitude() + "";
                String Longitude = info.getLongitude() + "";
                if (TextUtils.isEmpty(Latitude) || TextUtils.isEmpty(Longitude)) {
                    return;
                }
                sendLocation(Latitude, Longitude);
                ToastUtils.showShortToast(PaiDanService.this, "获取中..." + count);
                count++;
                showNitification();
                Log.d(TAG, "successGetLocation() called with: info = [" + info + "]");
            }


        }

        @Override
        public void error(String error) {
            Log.d(TAG, "error() called with: error = [" + error + "]");
        }

        private void refreshToken() {
            if (locationTools != null) {
                locationTools.stopLocation();
            }
            Boolean sucRef = RefReshToken.refshToken();
            if (sucRef) {
                initLocationTools();
                locationTools.startLocation(0);
            } else {
                RefReshToken.exitLogin();
            }
        }

        private void sendLocation(String Latitude, String Longitude) {
            if (isPlayningNewOrder) return;
            App.getApp().getHttpTools().getPaiDan("", Latitude, Longitude, new RequestCallBack<String>() {

                @Override
                public void onSuccess(String s) {
                    Log.e(TAG, "sendLocationonSuccess: S=" + s);
//                    try {
//                        JSONObject obj = new JSONObject(s);
//                        if (obj == null) {
//                            refreshToken();
//                            return;
//                        }
//                        int code = obj.getInt("state");
//                        if (code == 401) {
//                            //token过期刷新
//                            refreshToken();
//                            return;
//                        }
//
//                        if (code == 1) {
//                            int data = obj.getInt("data");
//
//                            if (data > 0) {
//                                showNitification(data + "");
//                            }
//                        }
//                        obj = null;
//
//
//                    } catch (Exception e) {
//                        Log.e(TAG, "------err------" + "Exception:" + e.toString());
//                    }
                }

                @Override
                public void onError(Throwable ex, boolean isOnCallback) {
                    Log.e(TAG, "------err------" + "网络错误:" + ex.toString());
                }

                @Override
                public void onCancelled(Callback.CancelledException cex) {

                }

                @Override
                public void onFinished() {

                }
            });
            System.gc();
            System.gc();
        }


    };

    @Override
    public void startWork(Intent intent, int flags, int startId) {
        Log.i(TAG, "startWork:  =====================isRunning=" + isRunning);
        if (!isRunning || locationTools == null) {
            initLocationTools();
            locationTools.startLocation(0);
            showNitification();
            isRunning = true;
        }


    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        initLocationTools();
        isRunning = false;
    }

    private void showNitification(String count) {

        if (isPlayningNewOrder) return;
        isPlayningNewOrder = true;
        if (locationTools != null) {
            locationTools.stopLocation();
            locationTools = null;
        }
        NotifyUtil.init(this);
        NotifyUtil.cancel(NOT_ID2);
        BaseBuilder builder = NotifyUtil.buildSimple(NOT_ID2, R.mipmap.icon, "营维189-新订单提示", "有新的订单了，点击进行处理,未处理订单数量:" + count, NotifyUtil.buildIntent(DispatchActivity.class))
                .setHeadup();
        builder = builder.setAction(false, true, true);
        builder = builder.setSmallIcon(R.mipmap.icon);
        builder.setTicker("发现新的订单了");
        builder.show();
        play();


    }

    @Override
    public void onCompletion(MediaPlayer mp) {
        initLocationTools();
        locationTools.startLocation(10000);
        if (mediaPlayer != null) {
            mediaPlayer.reset();
            mediaPlayer.release();
            mediaPlayer = null;
        }
        isPlayningNewOrder = false;

    }

    private void play() {
        try {
            mediaPlayer = MediaPlayer.create(this, RES_ID);//重新设置要播放的音频
            mediaPlayer.setOnCompletionListener(this);

        } catch (Exception e) {
            e.printStackTrace();//输出异常信息
        }
        mediaPlayer.start();//开始播放
    }

    private void showNitification() {
        NotifyUtil.init(this);
        NotifyUtil.cancel(NOT_ID);

        BaseBuilder builder = NotifyUtil.buildSimple(NOT_ID, R.mipmap.icon, "营维189", "派单任务已启动" + count, NotifyUtil.buildIntent(MainActivity.class))
                .setHeadup();
        builder = builder.setAction(false, false, true);
        builder = builder.setSmallIcon(R.mipmap.icon);
        builder.setOnGoing();
        builder.autoClean = false;
        builder.setTicker("派单任务运行中...");
        builder.show();
    }

    @Override
    public void stopWork(Intent intent, int flags, int startId) {
        Log.i(TAG, "stopWork:  \"----------------\" ");
        initLocationTools();
        // stopService();

    }

    /**
     * 任务是否正在运行?
     *
     * @return 任务正在运行, true; 任务当前不在运行, false; 无法判断, 什么也不做, null.
     */
    @Override
    public Boolean isWorkRunning(Intent intent, int flags, int startId) {
        //若还没有取消订阅, 就说明任务仍在运行.
        Log.i(TAG, "isWorkRunning:  任务是否正在运行?" + isRunning);
        return false;
    }

    @Override
    public IBinder onBind(Intent intent, Void v) {
        return null;
    }

    @Override
    public void onServiceKilled(Intent rootIntent) {
        isRunning = false;
        Log.i(TAG, "onServiceKilled: ==============================");
        if (locationTools != null) {
            locationTools.stopLocation();
        }
        locationTools = null;
    }


}
